import React from "react";
import "./jsonSchemaDocStyle.scss"
import {jsonSchemaToJson} from "../../../api/common/TestFunctionCommon";
import Mock from "mockjs";
import ReactMonacoEditor from "../../monacoEditor/MonacoEditor";
import {Space, Table, Tag, message} from "antd";
import {schemaToTable} from "../../JsonSchemaTable/JsonSchemaFn";
import DataTypeSelect from "../../DataTypeSelect";

const JsonSchemaDoc = ({schemaStr,isResponse}) =>{

    /**
     * 根据schema生成 模拟数据示例
     */
    const showEg = (schemaStr) =>{
        let processJson = jsonSchemaToJson(JSON.parse(schemaStr))
        let jsonData =JSON.stringify(Mock.mock(processJson))

        return  <ReactMonacoEditor
            value={jsonData}
            language={"json"}
            height={"150px"}
            readOnly={true}
        />
    }

    /**
     * 复制示例数据到剪贴板
     */
    const copy = () => {
        const processJson = jsonSchemaToJson(JSON.parse(schemaStr));
        const jsonData = JSON.stringify(Mock.mock(processJson), null, 2);
        navigator.clipboard.writeText(jsonData)
            .then(() => {
                // 这里可以添加复制成功的提示，比如使用 antd 的 message
                message.success('复制成功');
            })
            .catch(err => {
                message.error('复制失败');
                console.error('复制失败:', err);
            });
    }

    if(!schemaStr){
        schemaStr = JSON.stringify({
            "type": "object",
            "properties": {}
        })
    }

    return(
        <div className={"doc-json-content"}>

            <div>
                <Space style={{margin:"10px 0"}}><div>{isResponse?"响应体":"请求体参数"}</div><Tag>Json</Tag></Space>

                <div className={"doc-json-left-content"}>
                    <SchemaView schema={JSON.parse(schemaStr)}/>
                </div>
            </div>

            <div className={"doc-json-example"}>
                <div className={"doc-json-title"} >
                    <span>{isResponse?"响应示例":"请求示例"}</span>
                    <span onClick={copy} style={{cursor: 'pointer'}}>复制</span>
                </div>
                {
                    schemaStr && showEg(schemaStr)
                }
            </div>
        </div>
    )
}



const SchemaView = ({schema}) => {

    //表头
    let columns= [
        {
            title: '参数名称',
            dataIndex: 'name',
            width: "30%",
            editable: true,
            ellipsis:true,
            render:(text,record) =>  (showName(record))
        },{
            title: '必须',
            dataIndex: 'required',
            width: "10%",
            align:"center",
            render:(text,record) =>  (text?"是":"否")
        },{
            title: '数据类型',
            width: "20%",
            dataIndex: 'dataType',
            render: (text, record)=>(
                <DataTypeSelect
                    defaultValue={record.dataType}
                    rowData={record}
                    model={true}
                    disabled={true}
                    showArrow={false}
                />
            )
        },
        {
            title: '说明',
            dataIndex: 'description',
            editable: true,
            ellipsis:true
        },
    ]

    const showName = (record)=>{
        if(record.id==="root"){
            return <Tag color={"#f5f5f5"} style={{color:"gray"}} >根目录</Tag>
        }

        if(record.name==="ITEMS"){
            return <Tag color={"#f5f5f5"} style={{color:"gray"}}>ITEMS</Tag>
        }

        return record.name;
    }

    const dataSource = (schema) => {
        const initSchema = {
            id: 'root',
            name: 'root',
            dataType: 'object', // 默认数据类型
            mock: '',
            description: '',
            required: true,
        }
        let tableList;
        if(schema){
            tableList = [{
                ...initSchema,
                children: schemaToTable(schema.properties, schema.required)
            }];
        }else {
            tableList = [initSchema];
        }
        return tableList;
    }


    return (
        <div className={"pi-list-box"}>
            <Table
                bordered
                pagination={false}
                rowKey={record => record.id}
                defaultExpandAllRows={true}
                dataSource={dataSource(schema)}
                columns={columns}
            />
        </div>

    );
}


export default JsonSchemaDoc;